<template>
  <div class="progress-update-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="header-content">
          <span>项目进度管理</span>
          <div class="header-right">
            <!-- 修正 el-select 组件 -->
            <el-select
                v-model="selectedProject"
                filterable
                allow-create
                @change="handleProjectChange"
                style="margin-right: 20px; width: 200px;"
                placeholder="选择或输入项目"
            >
              <!-- 确保 value 绑定为字符串 -->
              <el-option
                  v-for="project in projectList"
                  :key="project.id"
                  :label="project.projectName"
                  :value="project.projectName"
              ></el-option>
            </el-select>
            <el-progress
                :percentage="progressPercentage"
                :stroke-width="18"
                status="success"
                style="width: 300px;"
            ></el-progress>
          </div>
        </div>
      </div>

      <!-- 任务管理 -->
      <div class="section">
        <h3>任务管理</h3>
        <el-form :model="form" ref="form">
          <el-input
              v-model="form.newTask"
              placeholder="请输入新任务"
              style="width: 400px; margin-right: 10px"
          ></el-input>
          <el-button
              type="primary"
              @click="addNewTask"
          >
            添加任务
          </el-button>
        </el-form>
        <!-- 任务列表 -->
        <el-table
            :data="currentProjectData.tasks"
            style="margin-top: 20px"
            empty-text="暂无任务">
          <el-table-column width="50">
            <template slot-scope="scope">
              <el-checkbox
                  v-model="scope.row.completed"
                  @change="updateTaskStatus(scope.row)"
              ></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column prop="task" label="任务内容">
            <template slot-scope="scope">
              <span :class="{ 'completed-task': scope.row.task }">
                {{ scope.row.task }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="最后更新时间" width="180"></el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button
                  type="text"
                  icon="el-icon-delete"
                  @click="removeTask('tasks', scope.$index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 遇到的问题 -->
      <div class="section">
        <h3>遇到的问题</h3>
        <el-form :model="form">
<!--          <el-button-->
<!--              type="primary"-->
<!--              @click="addIssue"-->
<!--              style="margin-top: 10px"-->
<!--          >-->
<!--            添加问题-->
<!--          </el-button>-->
        </el-form>
        <el-collapse style="margin-top: 20px">
          <el-collapse-item
              v-for="(issue, index) in currentProjectData.issues"
              :key="index"
              :title="issue.problem"
          >
            <div>记录时间：{{ issue.createTime }}</div>
            <el-button
                type="text"
                icon="el-icon-delete"
                @click="removeTask('issues', index)"
            ></el-button>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedProject: '', // 改为字符串类型，存储当前选中的项目名
      currentProjectData: { // 替换原来的 projects 对象，存储当前项目数据
        tasks: [],
        nextSteps: [],
        issues: []
      },
      projectList: [],       // 从后端获取的项目列表
      form: {
        newTask: '',
        newNextStep: '',
        newIssue: ''
      }
    };
  },
  computed: {
    progressPercentage() {
      const tasks = this.currentProjectData.tasks;
      if (tasks.length === 0) return 0;
      const completed = tasks.filter(t => t.completed).length;
      return Math.round((completed / tasks.length) * 100);
    }
  },
  created() {
    this.fetchProjects();
  },
  methods: {
    // 获取项目列表
    async fetchProjects() {
      try {
        const res = await this.$request.get('/project/selectUserProject');
        this.projectList = res.data;

        if (this.projectList.length === 0) {
          await this.createDefaultProject();
        } else {
          this.selectedProject = this.projectList[0].projectName;
          await this.fetchProjectData(this.selectedProject);
        }
      } catch (error) {
        this.$message.error('获取项目列表失败');
        // 网络异常时尝试加载本地默认项目
        if (this.projectList.length === 0) {
          this.loadLocalDefaultProject();
        }
      }
    },

    // 新增方法：创建默认项目
    async createDefaultProject() {
      try {
        const res = await this.$request.post('/api/projects', {
          name: '默认项目',
          tasks: [],
          nextSteps: [],
          issues: []
        });

        this.projectList.push(res.data.name);
        this.selectedProject = res.data.name;
        this.currentProjectData = res.data;
      } catch (error) {
        this.$message.error('创建默认项目失败');
        this.loadLocalDefaultProject();
      }
    },

    // 新增方法：加载本地默认项目（当后端不可用时）
    loadLocalDefaultProject() {
      this.projectList = ['默认项目'];
      this.selectedProject = '默认项目';
      this.currentProjectData = {
        tasks: [{
          id: Date.now(),
          content: "示例任务",
          completed: false,
          time: new Date().toLocaleString()
        }],
        nextSteps: [],
        issues: []
      };
    },


    // 获取项目详情
    async fetchProjectData(projectName) {
      try {
        const res = await this.$request.get(`/project/selectCurrentProjectData?projectName=${encodeURIComponent(this.selectedProject)}`);
        this.currentProjectData = res.data;
      } catch (error) {
        this.$message.error('获取项目数据失败');
      }
    },

    // 项目切换处理
    async handleProjectChange(val) {
      await this.fetchProjectData(val);

    },

    // 添加新任务
    async addNewTask() {
      if (!this.form.newTask.trim()) return;

      try {
        const res = await this.$request.post('/project/addTask', {
          project: this.selectedProject,
          content: this.form.newTask
        });

        this.currentProjectData.tasks.unshift(res.data);
        this.form.newTask = '';
      } catch (error) {
        this.$message.error('添加任务失败');
      }
    },

    // 更新任务状态
    async updateTaskStatus(task) {
      try {
        await this.$request.post(`/project/updateTaskStatus?id=${encodeURIComponent(task.id)}`, {
          completed: task.completed
        });
        task.createTime = new Date().toLocaleString();
      } catch (error) {
        this.$message.error('更新任务状态失败');
      }
    },

    // 删除任务
    async removeTask(type, index) {
      const item = this.currentProjectData[type][index];
      try {
        await this.$request.delete(`/api/${type}/${item.id}`);
        this.currentProjectData[type].splice(index, 1);
      } catch (error) {
        this.$message.error('删除失败');
      }
    },


    // 添加问题
    async addIssue() {
      if (!this.form.newIssue.trim()) return;

      try {
        const res = await this.$request.post('/api/issues', {
          project: this.selectedProject,
          content: this.form.newIssue
        });

        this.currentProjectData.issues.unshift(res.data);
        this.form.newIssue = '';
      } catch (error) {
        this.$message.error('添加问题失败');
      }
    },

    getCurrentTime() {
      return new Date().toLocaleString();
    }
  }
};
</script>
<style scoped>
.completed-task {
  text-decoration: line-through;
  color: #909399;
}

.progress-update-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
}

.section {
  margin-bottom: 30px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

h3 {
  color: #409EFF;
  margin-bottom: 15px;
}

.el-table::before {
  height: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-top: 10px;
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-right {
    width: 100%;
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>